<?php

namespace app\common\service;

use api\channel\meituan\alliance\Seckill;
use app\common\facade\supplier\Supplier;
use app\model\CouponOrderSid;
use think\facade\Db;

/**
 * 美团分销联盟
 * 秒杀的   @var Seckill
 */
class MeituanPub
{
    private $appKey = '';
    private $utmSource = '';
    private $activity = '';
    private $promotionId = '';
    private $platformId = 2;

    public function __construct($agentId)
    {
//        $api = Db::name('meituan_pub')
//            ->where('agent_id', $agentId)
//            ->find();
//        if (empty($api)) {
//            throw new \think\Exception('美团分销账号未配置');
//        }

        $supplier = Supplier::init(PRODUCT_METUAN_SERV);


        try {
            $this->appKey = $supplier->getAppkey();
            $this->utmSource = $supplier->getUtmSource();
            $this->promotionId = $supplier->getPromotionId();
        } catch (\Exception $e) {
            throw new \think\Exception($e->getMessage());
        }
    }

    /**
     * 团购API-省份查询接口
     */
    public function provinceAll()
    {
        $query = $this->getUrlQuery([
            'platformId' => $this->platformId,
        ]);
        $url = 'https://union.dianping.com/api/province/all?' . $query;
        $res = curlGet($url);
        $res = json_decode($res, true);
        return $res;
    }

    /**
     * 团购API-获取某个省份中城市信息
     */
    public function provinceCities($provinceId)
    {
        $query = $this->getUrlQuery([
            'platformId' => $this->platformId,
            'provinceId' => $provinceId,
        ]);
        $url = "https://union.dianping.com/api/province/$provinceId/cities?" . $query;
        $res = curlGet($url);
        $res = json_decode($res, true);
        return $res;
    }

    /**
     * 团购API-获取某个城市的一级类目包含的二级类目信息
     */
    public function cityCategories($cityId, $cat0Id = 0)
    {
        $query = $this->getUrlQuery([
            'platformId' => $this->platformId,
            'cityId' => $cityId,
            'cat0Id' => $cat0Id,
        ]);
        $url = "https://union.dianping.com/api/city/$cityId/categories?" . $query;
        $res = curlGet($url);
        $res = json_decode($res, true);
        return $res;
    }

    /**
     * 团购API-获取某个城市的商圈信息(美团)
     */
    public function mtCityRegions($cityId)
    {
        $query = $this->getUrlQuery([
            'cityId' => $cityId,
        ]);
        $url = "https://union.dianping.com/api/mt/city/$cityId/regions?" . $query;
        $res = curlGet($url);
        $res = json_decode($res, true);
        return $res;
    }

    /**
     * 团购API-获取某个城市的商圈信息(点评)
     */
    public function cityRegions($cityId)
    {
        $query = $this->getUrlQuery([
            'cityId' => $cityId,
        ]);
        $url = "https://union.dianping.com/api/city/$cityId/regions?" . $query;
        $res = curlGet($url);
        $res = json_decode($res, true);
        return $res;
    }

    /**
     * 团购API-团单查询接口
     */
    public function searchDeals($params)
    {
        $url = 'https://union.dianping.com/api/search/deals?' . $this->getUrlQuery();
        // 推广位规则：用户id + 's' + 代理商id + 's' + 渠道id
//        $utmMedium = $params['user_id'].'s'.$params['agent_id'].'s'.$params['channel_id'];
        $utmMedium = CouponOrderSid::generate($params['agent_id'],$params['channel_id'],$params['user_id'],0,PRODUCT_METUAN_SERV);
        $data = [
            'platformId' => $this->platformId,
            'utmSource' => $this->utmSource,
            'utmMedium' => $this->encrypt($utmMedium),
            'promotionId' => $this->promotionId,
            'cat0Id' => $params['cat0_id'],  // 餐饮
            'geo' => $params['geo'],
            'page' => $params['page'] ?? 1,
            'size' => $params['size'] ?? 10,
        ];
        if (!empty($params['shop_id'])) {
            $data['shopIds'] = [$params['shop_id']];
        }
        if (!empty($params['cat1_id'])) {
            $data['cat1Id'] = $params['cat1_id'];
        }
        if (!empty($params['sort_type'])) {
            $data['sortType'] = $params['sort_type'];
        }
        if (!empty($params['keyword'])) {
            $data['keyWords'] = $params['keyword'];
        }
        $header = [
            'User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/91.0.4472.77 Safari/537.36',
            'Content-Type: application/json'
        ];

        $res = curlPost($url, json_encode($data, JSON_UNESCAPED_UNICODE), $header);
        $res = json_decode($res, true);
        return $res;
    }

    /**
     * 秒杀API-秒杀场次信息接口
     */
    public function seckillShowInfo($cityId)
    {
        $query = $this->getUrlQuery([
            'version' => '1.0',
            'platformId' => 2,
            'cityId' => $cityId,
        ]);
        $url = "https://union.dianping.com/api/seckill/showInfo?" . $query;
        $res = curlGet($url);
        $res = json_decode($res, true);
        return $res;
    }

    /**
     * 订单数据API-CPS订单数据接口
     *
     * @params  $startTime  开始时间
     * @params  $endTime    结束时间
     * @params  $page       页数
     * @params  $size       每页结果数
     */
    public function cpsOrderList($params)
    {
        $query = [
            'promotionId' => $this->promotionId,
            // 'queryType' => 1,
            // 'startTime' => $params['startTime'],
            // 'endTime' => $params['endTime'],
            'page' => $params['page'] ?? 1,
            'size' => $params['size'] ?? 100,
        ];
        if (isset($params['startTime'])) {
            $query['startTime'] = $params['startTime'];
            $query['endTime'] = $params['endTime'];
            $query['queryType'] = 1;
        } else {
            $query['uniqueItemIds'] = [$params['order_id']];
        }
        $query = $this->getUrlQuery($query);
        $url = 'https://union.dianping.com/data/promote/verify/item?' . $query;

        $res = curlGet($url);
        $res = json_decode($res, true);
        return $res;
    }

    public function getUrlQuery($data = [])
    {
        $timestamp = time();
        $params = [
            'requestId' => $timestamp,
            'utmSource' => $this->utmSource,
            'version' => '1.0',
            'accessToken' => $this->encrypt($this->utmSource . $timestamp),
            'timestamp' => $timestamp,
        ];
        if ($data) {
            $params = array_merge($params, $data);
        }
        return http_build_query($params);
    }

    public function encrypt($data)
    {
        return bin2hex(openssl_encrypt($data, 'AES-128-ECB', $this->appKey, OPENSSL_RAW_DATA));
    }

    public function decrypt($data)
    {
        return openssl_decrypt(hex2bin($data), 'AES-128-ECB', $this->appKey, OPENSSL_RAW_DATA);
    }
}
